using Newtonsoft.Json;
using LiJ.Common.Core;
using LiJ.Common.Plugs.LogPlug;
using LiJ.Http.Mos;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace LiJ.Http.Extention
{
	/// <summary>
	/// 通用请求结果扩展
	/// </summary>
	public static class LRestExtention
	{
		/// <summary>
		/// 处理远程请求方法，并返回需要的实体
		/// </summary>
		/// <typeparam name="T">需要返回的实体类型</typeparam>
		/// <param name="request">远程请求组件的request基本信息</param>
		/// <param name="formatFunc">处理内容委托</param>
		/// <param name="client">自定义httpclient</param>
		/// <param name="moduleName">模块名称</param>
		/// <returns>实体类型</returns>
		public static async Task<T> RestCommon<T>(this LHttpRequest request, Func<HttpResponseMessage, Task<T>> formatFunc, HttpClient client = null, string moduleName = "default") where T : ResultMo, new()
		{
			T val;
			try
			{
				val = await formatFunc(await request.RestSend(client));
			}
			catch (Exception ex)
			{
                var val2 = new T
                {
                    Ret = 1500,
                    Msg = ex.Message
                };
                val = val2;
				LogUtil.Error("基类请求出错，错误信息：" + ex.Message, "RestCommon", moduleName);
			}
			object val3 = val;
			if (val3 == null)
			{
				val3 = new T();
				((T)val3).Ret = -1;
				((T)val3).Msg = "未发现结果";
			}
			return (T)val3;
		}

		/// <summary>
		///  使用json格式化内容方法
		/// </summary>
		/// <typeparam name="TResp"></typeparam>
		/// <param name="resp"></param>
		/// <returns></returns>
		private static async Task<TResp> JsonFormat<TResp>(HttpResponseMessage resp) where TResp : ResultMo, new()
		{
			if (!resp.IsSuccessStatusCode)
			{
				TResp val = new TResp();
				val.Ret = (int) (0 - resp.StatusCode);
				val.Msg = resp.ReasonPhrase;
				return val;
			}
			return JsonConvert.DeserializeObject<TResp>(await resp.Content.ReadAsStringAsync());
		}

		/// <summary>
		///
		/// </summary>
		/// <typeparam name="TResp"></typeparam>
		/// <param name="request"></param>
		/// <param name="client"></param>
		/// <param name="moduleName"></param>
		/// <returns></returns>
		public static async Task<TResp> RestCommonJson<TResp>(this LHttpRequest request, HttpClient client = null, string moduleName = "default") where TResp : ResultMo, new()
		{
			return await RestCommon(request, JsonFormat<TResp>, client, moduleName);
		}
	}
}
